//
//  BIDDetailEmailFromOutboxViewController.m
//  shangwuting
//
//  Created by mal on 13-12-26.
//  Copyright (c) 2013年 mal. All rights reserved.
//

#import "BIDDetailEmailFromOutboxViewController.h"
#import "BIDShowPhotoView.h"
#import "BIDDownloadFile.h"
#import "BIDShowDocView.h"
#import "BIDMenuView.h"
#import "BIDTransmitEmailViewController.h"
#import "BIDAccessoryListCanOpenViewController.h"
#import "BIDEmailReceiveConditionViewController.h"
#import "BIDReadConditionView.h"

//邮件详情
static NSString *emailDetailURL = @"emailReplyAndroid!toReadInbox.action";
//下载附件
static NSString *downloadURL = @"emailAndroid!download.action";
//删除邮件
static NSString *deleteURL = @"emailAndroid!dropSendedEmail.action";

@interface BIDDetailEmailFromOutboxViewController ()<BIDShowPhotoViewDelegate, BIDDownloadFileDelegate, BIDMenuViewDelegate>
{
    BIDMenuView *_menuView;
    BOOL _bShowMenu;
}
@property (strong, nonatomic)NSMutableArray *imgArr;
@end

@implementation BIDDetailEmailFromOutboxViewController
@synthesize titleLabel;
@synthesize timeLabel;
@synthesize contentLabel;
@synthesize showPhotoView;
@synthesize myTableView;
@synthesize bgImgView1;
@synthesize lineLabel;
@synthesize emailId;
@synthesize photosArr;
@synthesize photosDataArr;
@synthesize docsArr;
@synthesize downloadFile;
@synthesize showDocView;
@synthesize willOpenFileName;

@synthesize readConditionView;
@synthesize myScrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"邮件详情";
    // Do any additional setup after loading the view from its nib.
    photosDataArr = [[NSMutableArray alloc] initWithCapacity:1];
    [self adjustLayout];
    [contentLabel setBackgroundColor:[UIColor clearColor]];
    [contentLabel setFont:[UIFont systemFontOfSize:[AppDelegate getFontSize]]];
    contentLabel.numberOfLines = 0;
    
    //设置拍照视图
    int interval = 2;
    int intervalFromPhotoViewToTextView = 15;
    CGSize ownSize = self.view.frame.size;
    CGSize showPhotoViewSize = CGSizeMake(ownSize.width-interval*2, 100);
    CGRect showPhotoViewFrame = CGRectMake(interval, contentLabel.frame.origin.y+contentLabel.frame.size.height+intervalFromPhotoViewToTextView, showPhotoViewSize.width, showPhotoViewSize.height);
    showPhotoView = [[BIDShowPhotoView alloc] initWithFrame:showPhotoViewFrame];
    showPhotoView.photoCount = 3;
    showPhotoView.addPhotoBtn.hidden = YES;
    showPhotoView.bCanDelete = NO;
    showPhotoView.bCanSave = NO;
    showPhotoView.bNeedScale = YES;
    [myScrollView addSubview:showPhotoView];
    showPhotoView.delegate = self;
    
    //
    downloadFile = [[BIDDownloadFile alloc] init];
    downloadFile.delegate = self;
    downloadFile.saveDirectory = @"downloads/doc/";
    [downloadFile initData];
    
    //文档视图
    showDocView = [[BIDShowDocView alloc] init];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_more.png"] style:UIBarButtonItemStylePlain target:self action:@selector(functionHandler)];
    
    [self loadContent];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    titleLabel = nil;
    timeLabel = nil;
    contentLabel = nil;
    showPhotoView = nil;
    myTableView = nil;
    photosArr = nil;
    photosDataArr = nil;
    docsArr = nil;
    downloadFile = nil;
    showDocView = nil;
    bgImgView1 = nil;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [showPhotoView removeFromSuperview];
    showPhotoView = nil;
    downloadFile = nil;
}

/**
 *  更多
 */
- (void)functionHandler
{
    //弹出菜单
    if(!_menuView)
    {
        NSArray *menuNameArr = @[@"已下附件", @"转发邮件", @"接收情况", @"删除邮件"];
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        //menuWidth,menuHeight,triangleWidth,triangleHeight,triangleToRight
        BIDMenuAttribute menuAttribute = {120, 5, 10, 15, 14};
        int menuViewPosX = screenSize.width - 26 - (menuAttribute.menuWidth-menuAttribute.triangleToRight-menuAttribute.triangleWidth/2);
        int menuViewPosY = 2;
        _menuView = [[BIDMenuView alloc] initWithFrame:CGRectMake(menuViewPosX, menuViewPosY, menuAttribute.menuWidth, menuAttribute.menuHeight) menuNameArr:menuNameArr imgNameArr:nil menuAttribute:menuAttribute];
        _menuView.delegate = self;
    }
    if(!_bShowMenu)
    {
        _bShowMenu = YES;
        [self.view addSubview:_menuView];
    }
    else
    {
        _bShowMenu = NO;
        [UIView animateWithDuration:1.0f animations:^{
            //_menuView.transform = CGAffineTransformMakeScale(0.5f, 0.5f);
        } completion:^(BOOL bFinished){
            if(bFinished)
            {
                [_menuView removeFromSuperview];
            }
        }];
    }
}

#pragma mark - BIDMenuViewDelegate
- (void)selectMenuAtIndex:(int)index
{
    _bShowMenu = NO;
    switch(index)
    {
        case 0:
        {
            //已下附件
            BIDAccessoryListCanOpenViewController *accessoryListViewController = [[BIDAccessoryListCanOpenViewController alloc] init];
            [self.navigationController pushViewController:accessoryListViewController animated:YES];
        }
            break;
        case 1:
        {
            //转发邮件
            BIDTransmitEmailViewController *transmitEmailViewController = [[BIDTransmitEmailViewController alloc] initWithNibName:@"BIDTransmitEmailViewController" bundle:nil];
            transmitEmailViewController.emailId = emailId;
            [self.navigationController pushViewController:transmitEmailViewController animated:YES];
        }
            break;
        case 2:
        {
            //接收情况
            BIDEmailReceiveConditionViewController *conditionViewController = [[BIDEmailReceiveConditionViewController alloc] init];
            conditionViewController.emailId = emailId;
            [self.navigationController pushViewController:conditionViewController animated:YES];
        }
            break;
        case 3:
        {
            //删除
            [self deleteEmail];
        }
            break;
    }
}

- (void)deleteEmail
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], deleteURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"ids=%@", emailId];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(responseDic)
        {
            NSNumber *value = [responseDic objectForKey:@"isSuccess"];
            if([value intValue]==1)
            {
                [BIDGlobalMethods showAlertView:@"删除成功" buttonTitle:ALERT_BTN_TITLE delegate:self tag:1];
            }
            else
            {
                [BIDGlobalMethods showAlertView:@"删除失败" buttonTitle:ALERT_BTN_TITLE delegate:nil tag:0];
            }
        }
    }];
}

- (void)loadContent
{
    NSString *strURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], emailDetailURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"emailId=%@", emailId];
    [self sendHttpRequestWithURL:strURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(responseDic)
        {
            NSDictionary *dictionary = responseDic;
            NSDictionary *emailDictionary = [dictionary objectForKey:@"email"];
            titleLabel.text = [emailDictionary objectForKey:@"title"];
            timeLabel.text = [emailDictionary objectForKey:@"time"];
            contentLabel.text = [emailDictionary objectForKey:@"content"];
            //
            CGSize contentLabelSize = [contentLabel.text sizeWithFont:contentLabel.font constrainedToSize:CGSizeMake(contentLabel.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
            CGFloat contentHeight = contentLabelSize.height>82?contentLabelSize.height:82;
            CGRect contentLabelFrame = contentLabel.frame;
            contentLabelFrame.size.height = contentHeight;
            contentLabel.frame = contentLabelFrame;
            //lineLabel
            CGRect lineLabelFrame = lineLabel.frame;
            lineLabelFrame.origin.y = contentLabel.frame.origin.y + contentLabel.frame.size.height + 3;
            lineLabel.frame = lineLabelFrame;
            //
            CGRect photoViewFrame = showPhotoView.frame;
            photoViewFrame.origin.y = lineLabel.frame.origin.y + lineLabel.frame.size.height + 15;
            showPhotoView.frame = photoViewFrame;
            //
            CGRect tableViewFrame = myTableView.frame;
            tableViewFrame.origin.y = showPhotoView.frame.origin.y + showPhotoView.frame.size.height + 10;
            myTableView.frame = tableViewFrame;
            //
            NSArray *arr = [dictionary objectForKey:@"photos"];
            photosArr = [[NSMutableArray alloc] initWithArray:arr];
            //加载图片
            [self loadPhotos];
            docsArr = [dictionary objectForKey:@"others"];
            CGRect readConditionFrame = CGRectMake(myTableView.frame.origin.x, 0, myTableView.frame.size.width, 0);
            
            if(docsArr.count==0)
            {
                readConditionFrame.origin.y = myTableView.frame.origin.y;
                myTableView.hidden = YES;
            }
            else
            {
                [myTableView reloadData];
                tableViewFrame = myTableView.frame;
                tableViewFrame.size.height = docsArr.count * 25;
                myTableView.frame = tableViewFrame;
                readConditionFrame.origin.y = myTableView.frame.origin.y + myTableView.frame.size.height + 10;
            }
            //接收情况
//            NSArray *titlesArr = [[NSArray alloc] initWithObjects:@"已读:", @"未读:", nil];
//            NSString *strReaded = [dictionary objectForKey:@"isRead"];
//            NSString *strNotRead = [dictionary objectForKey:@"notRead"];
//            NSArray *contentArr = [[NSArray alloc] initWithObjects:strReaded, strNotRead, nil];
//            readConditionView = [[BIDReadConditionView alloc] initWithFrame:readConditionFrame titlesArr:titlesArr contentArr:contentArr];
//            [myScrollView addSubview:readConditionView];
//            CGRect readConditionViewFrame = readConditionView.frame;
            //CGFloat viewContentHeight = readConditionViewFrame.origin.y + readConditionViewFrame.size.height + 10;
            CGFloat viewContentHeight = readConditionFrame.origin.y + 10;
            CGSize contentSize = myScrollView.contentSize;
            contentSize.height = viewContentHeight;
            myScrollView.contentSize = contentSize;
        }
        
    }];
}

//调整布局
- (void)adjustLayout
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect ownFrame = self.view.frame;
    ownFrame.size.height = screenSize.height-64;
    self.view.frame = ownFrame;
    
    CGRect scrollViewFrame = myScrollView.frame;
    scrollViewFrame.size.height = screenSize.height-64;
    myScrollView.frame = scrollViewFrame;
    
    CGRect frame = myTableView.frame;
    frame.size.height = ownFrame.size.height-8-frame.origin.y;
    myTableView.frame = frame;
    
    bgImgView1.frame = myTableView.frame;
    myTableView.backgroundView = bgImgView1;
}

//加载图片并显示
- (void)loadPhotos
{
    if(photosArr.count>0)
    {
        [self showSpinnerView];
        dispatch_group_t group = dispatch_group_create();
        for(int i=0; i<photosArr.count; i++)
        {
            NSDictionary *dictionary = [photosArr objectAtIndex:i];
            dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
                NSString *strId = [dictionary objectForKey:@"id"];
                NSString *strURL = [[NSString alloc] initWithFormat:@"%@/%@?emailId=%@", [AppDelegate getServerAddr], downloadURL, strId];
                NSString *strFileName = [dictionary objectForKey:@"fileName"];
                NSMutableData *data = [NSMutableData data];
                [BIDDataCommunication getDataFromNet:strURL data:data];
                NSDictionary *dictionary1 = [[NSDictionary alloc] initWithObjectsAndKeys:strFileName, @"fileName", data, @"data", nil];
                [photosDataArr addObject:dictionary1];
            });
        }
        dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideSpinnerView];
                for(int i=0; i<photosDataArr.count; i++)
                {
                    NSDictionary *dataDictionary = [photosDataArr objectAtIndex:i];
                    NSData *data = [dataDictionary objectForKey:@"data"];
                    UIImage *img = [UIImage imageWithData:data];
                    [self.showPhotoView addPhoto:img];
                }
            });
        });
    }
    else
    {
        //当没有图片时，展示附件的列表需要改变下位置
        showPhotoView.hidden = YES;
        CGRect frame = showPhotoView.frame;
        CGRect tableViewFrame = myTableView.frame;
        tableViewFrame.origin.y = frame.origin.y;
        myTableView.frame = tableViewFrame;
    }
}

#pragma mark BIDShowPhotoViewDelegate
- (void)changeStatusForStatusBar:(NSInteger)type
{
    if(type==1)
    {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
    }
    else
    {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

- (void)passValueOpenDoc
{
    [showDocView openDoc:willOpenFileName];
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [docsArr count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"identifier";
    NSUInteger row = [indexPath row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSDictionary *dictionary = [docsArr objectAtIndex:row];
    NSString *strFileName = [dictionary objectForKey:@"fileName"];
    NSString *strFileSize = [dictionary objectForKey:@"size"];
    strFileSize = [[NSString alloc] initWithFormat:@"(%@)", strFileSize];
    NSUInteger len1 = strFileName.length;
    NSUInteger len2 = strFileSize.length;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[[NSString alloc] initWithFormat:@"%@%@", strFileName, strFileSize]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, len1)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:47.0f/255.0f green:132.0f/255.0f blue:61.0f/255.0f alpha:1.0f] range:NSMakeRange(len1, len2)];
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, len1)];
    cell.textLabel.attributedText = str;
    cell.textLabel.font = [UIFont systemFontOfSize:13.0f];
    [cell setBackgroundColor:[UIColor clearColor]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    NSDictionary *dictionary = [self.docsArr objectAtIndex:row];
    NSString *strFileName = [dictionary objectForKey:@"fileName"];
    willOpenFileName = strFileName;
    
    if([BIDGlobalMethods IsFileExist:strFileName])
    {
        [showDocView openDoc:strFileName];
    }
    else
    {
        //先下载
        NSString *accessoryId = [dictionary objectForKey:@"id"];
        NSString *downloadURL = [[NSString alloc] initWithFormat:@"%@/%@?emailId=%@", [AppDelegate getServerAddr], downloadURL, accessoryId];
        downloadFile.fileName = strFileName;
        [downloadFile downloadFile:downloadURL];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 22;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==1)
    {
        //删除成功
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
